#include "process_pool.h"

int make_child(process_data_t *p,int processNum)
{
    int sockFds[2];
    pid_t pid;
    for(int i = 0;i<processNum;++i)
    {
        int ret = socketpair(AF_LOCAL,SOCK_STREAM,0,sockFds);
        ERROR_CHECK(ret,-1,"socketpair");
        pid = fork();
        if(!pid)
        {
            close(sockFds[0]);//子进程关闭0口
            child_handle(sockFds[1]);
        }
        close(sockFds[1]);//父进程关闭1口
        //初始化父进程空间对子进程的描述
        p[i].pid = pid;
        p[i].fd = sockFds[0];
        p[i].busy = 0;
    }
    return 0;
}

int child_handle(int fds)
{
    int newFd = 0;
    char finishFlag = 0;
    struct timeval tstart,tend;
    while(1)
    {
        //接收任务
        recvFd(fds,&newFd);
        printf("Child (id : %d): recved mission ,newFd: %d . timer start! \n",getpid(),newFd);
        printf("Child (id : %d): task (fd: %d) data transfering...\n",getpid(),fds);
        gettimeofday(&tstart,NULL);
        trans_file(newFd);
        gettimeofday(&tend,NULL);
        printf("Child (id : %d): mission done,time use: %.2lf s\n",getpid(),\
               (double)((tend.tv_sec - tstart.tv_sec)*1000000+tend.tv_usec - tstart.tv_usec)/1000000.00);
        write(fds,&finishFlag,1);//用于通知父进程任务完成
        close(newFd);
    }
    printf("Child (id : %d): exiting...\n",getpid());
    exit(0);//注意这里必须写exit！
}
